layui.define(['helper', 'parsedata'], function (exports) {
	window.$ = layui.$;
	var parsedata = layui.parsedata;
	var openWidth = getPageWidth() < 960 ? '100%' : '80%';
	var obj = {
		//树形菜单表格
		init: function(api, id, treeTable, menuData){
			var cols = [{type:'checkbox'}];
			var field = menuData.table_struct.field;
			var primaryKey = menuData.table_struct.primary_key;
			var selected = [];
			for(i in field){
				if(field[i]['in_list'] === true){
					array_push(cols, {field:i, title: field[i]['label'],width: field[i]['width'], sort: true});
				}
			}
			array_push(cols, {fixed: 'right', width:menuData.operate_width, align:'center', toolbar: '#tbBar',title:'操作'});
			// 渲染表格
			window.insTb = treeTable.render({
				title: menuData.title,
				elem: '#'+id,
				url: api,
				toolbar: '#toolbarDemo',
				height: 'full-200',
				tree: {
					iconIndex: 2,
					isPidData: true,
					idName: menuData.table_struct.tree.id_name,
					pidName: menuData.table_struct.tree.pid_name
				}
				,defaultToolbar:['filter', 'print', 'exports',{
					title: '刷新'
				  ,layEvent: 'RELOAD'
				  ,icon: 'layui-icon-refresh'
				}],
				cols: [ cols ]
				
				,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
					var itemdata = res.data.data;
					for(i in itemdata){
						//开始解析数据
						var items = itemdata[i];
						for(ii in items){
							if(menuData.table_struct.tree.pid_name == ii){
								continue;
							}
							try{
								var parseFun = field[ii]['input_type'];
								var parseOption = field[ii]['value'];
								var item =  items[ii];							
								eval('item = parsedata.'+parseFun+'(item, parseOption);');
								if(in_array(ii, ['create_time', 'update_time']) && is_numeric(item) && item > 0 && parseFun == 'hidden'){
									item = formatDate(item * 1000, 'Y-M-D H:i:s');
								}
								itemdata[i][ii] = item;
							}catch(e){
								//TODO handle the exception
							}
							
						}
						if(in_array(itemdata[i][primaryKey], selected)){
							itemdata[i]['LAY_CHECKED'] = true;
						}
						
					}
					//没有带转换功能
					  return {
						  "code": res.errorcode, //解析接口状态
						  "msg": res.errormsg, //解析提示文本
						  "count": res.data.total, //解析数据长度
						  "data": itemdata //解析数据列表
					  };
				},
				
				style: 'margin-top:0;'
			});
			
			//表格监听
			//头工具栏事件
			treeTable.on('toolbar(demoTreeTb)', function(obj){
			  switch(obj.event){
				case 'add':
				  var addPage = './finder/add.html';
				  if(!empty(window.memuData.custom_tempadd)){
					addPage = window.memuData.custom_tempadd;
				  }
				  var _method_ = '';
				  if($(this).data('href')){
					  _method_ = $(this).data('href');
				  }
				  var href = addPage+'?api='+$_GET['api']+'&_method_='+_method_+'&toolbar=head';
				  layer.open({
					  type: 2,
					  title: "添加",
					  shadeClose: true,
					  scrollbar: false,
					  shade: 0.5,
					  offset:'r',
					  area: [openWidth, '100%'],
					  content: href, //iframe的url
					  cancel: function(){
						  if(window.toRefresh == true){
							  window.location.reload();
						  }
					  }
				  }); 
				break;
				case 'open':
				  layer.open({
					  type: 2,
					  title: $(this).data("title"),
					  shadeClose: true,
					  scrollbar: false,
					  shade: 0.7,
					  offset:'r',
					  area: ['50%', '100%'],
					  content: $(this).data("href")+"?toolbar=head"
				  });
				break;
				case 'submit':
				  var data = checkStatus.data;
					if(data == false) return noticeMsg("error", "请选择需要"+$(this).data("title")+"的数据");
					if($(this).data("href") == false)  return noticeMsg("error", "href地址未配置");
					var _method_ = $(this).data("href");
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
					    layer.closeAll();
						var where = '_method=POST&toolbar=head&';
						for(i in data){
						  where += primaryKey+'[]='+data[i][primaryKey]+'&';
						}
						if(strrpos(_method_, '/') >= 0){
							ajax_request(_method_, 'POST', where, function(res){
							try{
								if(res.errorcode == 0){
									noticeMsg("success", res.errormsg);
									table.reload(id);
								}
							}catch(e){
								layer.msg(res);
							}
						});
						}else{
							ajax_request($_GET['api']+"?_method_="+_method_, 'POST', where, function(res){
							try{
								if(res.errorcode == 0){
									noticeMsg("success", res.errormsg);
									table.reload(id);
								}
							}catch(e){
								layer.msg(res);
							}
						});
						}  
					});
				break;
				case 'delete':
					var data = insTb.checkStatus();
					//批量删除
					if(data == false) return noticeMsg("error", "请选择需要"+$(this).data("title")+"的数据");
							  
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
					  layer.closeAll();
					  var where = '_method=DELETE&';
					  for(i in data){
						where += primaryKey+'[]='+data[i][primaryKey]+'&';
					  }
					  ajax_request($_GET['api'], 'POST', where, function(res){
							layer.closeAll();
							var code = res.errorcode;
							if(code == 0){
								//全选的删除是要刷新的
								$(".layui-form-checked").each(function(i){
										var myObj = $(this).parent().parent().parent().parent();
										for(ii in data){
											if(data[ii][primaryKey] == myObj.find('td .ew-tree-table-cell-content').eq('1').html()){
												myObj.remove();
												//删除行
											}
										}
								 });
								noticeMsg("success","删除成功");
							}else{
								noticeMsg("error","删除失败");
							}
					  });
						
					});
				break;
				
				//自定义头工具栏右侧图标 - 提示
				case 'RELOAD':
					window.location.reload();
				break;
			  };
			});
			
			
			//监听行工具事件
			treeTable.on('tool(demoTreeTb)', function(obj){
			  var data = obj.data;
			  window.selectObj = obj;
			  if(obj.event === 'delete'){
				layer.confirm('确定要'+$(this).data("title")+"?", function(index){
				  layer.closeAll();
				  layerTableRowDelete($_GET['api']+'?_method=DELETE&'+primaryKey+'='+data[primaryKey], obj);//执行删除
				  //删除之后是不是还有一个删除页面的动作
				});
			  } else if(obj.event === 'edit'){
				var editPage = './finder/edit.html';
				if(!empty(window.memuData.custom_tempedit)){
					editPage = window.memuData.custom_tempedit;
				}
				var _method_ = '';
				if($(this).data('href') != false){
				   _method_ = $(this).data('href');
				}
				var href = editPage+'?api='+$_GET['api']+'&_method_='+_method_+'&toolbar=row&'+primaryKey+'='+data[primaryKey];
				layer.open({
				  type: 2,
				  title: $(this).data("title"),
				  shadeClose: true,
				  scrollbar: false,
				  shade: 0.2,
				  offset:'r',
				  area: [openWidth, '100%'],
				  content: href, //iframe的url
				}); 
			  }else if(obj.event === 'open'){
				layer.open({
					  type: 2,
					  title: $(this).data("title"),
					  shadeClose: true,
					  scrollbar: false,
					  shade: 0.2,
					  offset:'r',
					  area: [openWidth, '100%'],
					  content: $(this).data("href")+'?'+primaryKey+'='+data[primaryKey], //iframe的url
					}); 
			  }else if(obj.event === 'submit'){
					if($(this).data("href") == false)  return noticeMsg("error", "href地址未配置");
					var _method_ = $(this).data("href");
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
						layer.closeAll();
						var where = '_method=POST&';
					where += primaryKey+'[]='+data[primaryKey]+'&';
					if(strrpos(_method_, '/') >= 0){
						ajax_request(_method_, 'POST', where, function(res){
						try{
							if(res.errorcode == 0){
								noticeMsg("success", res.errormsg);
								table.reload(id);
							}
						}catch(e){
							layer.msg(res);
						}
					});
				}else{
					ajax_request($_GET['api']+"?toolbar=row&_method_="+_method_, 'POST', where, function(res){
						try{
							if(res.errorcode == 0){
								noticeMsg("success", res.errormsg);
								try{
									table.reload(id);
								}catch(e){
									//TODO handle the exception
								}
								
							}
						}catch(e){
							layer.msg(res);
						}
					});
				}
				  
			  });
			  }else if(obj.event === 'spread'){
				selectDetails(this, data[primaryKey]);
				//primaryKey+'='+data[primaryKey]
			}else{
				layer.msg("row_toolbar自定义event目前只支持"+"add,delete,open,submit", {
					icon : 2,time:3000,shift: 6
				});
			  }
			});
			
			
			// 全部展开
			$('#btnExpandAll').click(function () {
				insTb.expandAll();
			});
			
			// 全部折叠
			$('#btnFoldAll').click(function () {
				insTb.foldAll();
			});
			// 搜索
			$('#btnSearch').click(function () {
				var keywords = $('#edtSearch').val();
				if (keywords) {
					insTb.filterData(keywords);
				} else {
					insTb.clearFilter();
				}
			});
				
			// 清除搜索
			$('#btnClearSearch').click(function () {
				insTb.clearFilter();
			});
			
		},
	};
	window.layerTableRowDelete = function(url, obj){
	        //等待的效果呢
			ajax_request(url, 'POST', '', function(res){
				noticeMsg("success", "删除成功");
				obj.del();
				//关闭当前窗口
							
				//获取一下当前行数
				if($(".layui-table").eq($(".layui-table").length - 1).find('tr').length <= 0){
					//触发页面刷新
					window.location.reload();
				}
			});
	}
	exports('finderTree', obj);//导出
});